const socketWrapper = require('./index');
const { redisGet } = require('../utils/redis')
const { getFriendList } = require('../model/chatList')

// 等待 Socket.IO 初始化完成后再使用
function setChatList() {
    try {
        const io = socketWrapper.getIO();
        io.on('connection', async (socket) => {
            socket.on('chatList', async (data, callback = () => { }) => {
                const imKey = socket.imKey;
                const chatList = await getFriendList(imKey);
                const list = []
                for (let i = 0; i < chatList.length; i++) {
                    const item = JSON.parse(JSON.stringify(chatList[i]))
                    const checkImKey = item.user === imKey ? item.toUser : item.user;
                    const userInfo = await redisGet(`mim-${checkImKey}`);
                    item.imKey = checkImKey;
                    item.userName = userInfo?.userName;
                    item.avatar = userInfo?.avatar;
                    item.online = userInfo?.online;
                    item.uid = userInfo?.userId;
                    item.userType = userInfo?.userType;
                    list.push(item)
                }
                socket.emit('chatList', {
                    code: 200,
                    data: list
                })
                callback({
                    code: 200,
                    data: list
                });
            });
        });
    } catch (error) {
        console.error('Socket.IO 未初始化:', error);
        callback({
            code: 500,
            message: error.message
        });
    }
}

module.exports = setChatList;
